#version 120
uniform sampler2D ShadowMap;
uniform mat4 MCtoLightMatrix[100];
uniform mat4 ModelView;
uniform int nbLight;
uniform vec3 lightPos;

varying vec3 Normal;
varying vec4 Vertex;
varying vec4 Color;

float isShadow(vec2 coord, float depth){
    float dist = texture2D(ShadowMap, coord).z;
    float diff = exp( -80.0 * (depth - dist));
    if(diff >= 1.0)
        return 0.0;
    else
        return 1.0 - diff;
}

void main()
{
    float nbShadow = 0;
    float deltaTex = 1.0/nbLight;

    for(int i = 0; i < nbLight; i++)
    {
        vec4 shadowCoord = MCtoLightMatrix[i] * ModelView * Vertex;
        vec4 coord = shadowCoord / shadowCoord.w ;
        if(coord.x >= 0.0 && coord.x <= 1.0 && coord.y >= 0.0 && coord.y <= 1.0 )
        {
            coord.z -= 0.005;
            coord.x = coord.x/nbLight;

            if(shadowCoord.w > 0.0)
            {
                float conv = 0.0;
                nbShadow += isShadow(coord.xy, coord.z);
            }
            else
                nbShadow += 0.0;
        }
        else
            nbShadow += 0.0;
        coord.x += deltaTex;
    }
    float shadowIntensity = 1.0 - float(nbShadow)/nbLight;

    vec3 s = normalize( Vertex.xyz - lightPos );
    vec3 n = normalize(Normal);
    vec3 diffuse = vec3(max(0.0, -dot(n, s.xyz)))*0.9;
    vec3 ambient = vec3(0.1, 0.1, 0.1);

    vec3 col =  Color.rgb * ambient + (Color.rgb * diffuse * shadowIntensity);
    gl_FragColor = vec4(col.r, col.g, col.b, 1.0);
}
